package cn.modfun.common.charts.jfreechart;

import java.awt.Font;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.joda.time.DateTime;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ClassPathResource;

public class JFreeChartUtils {

	/**
	 * 设置默认主题
	 */
	public static void setTheme(){
		StandardChartTheme theme = new StandardChartTheme("CN");
		theme.setLargeFont(new Font("黑体", Font.BOLD, 20));
		theme.setExtraLargeFont(new Font("宋体", Font.PLAIN, 15));
		theme.setRegularFont(new Font("宋体", Font.PLAIN, 15));
	    ChartFactory.setChartTheme(theme);
	}
	/**
	 * 获得临时文件名
	 * @return
	 */
	public static String getTempChartImagePath(){
		/* 默认生成在classpath 下面 */
		String folder = new ClassPathResource("/").getFile().getAbsolutePath()+"/temp/jfreechart/"+DateTime.now().toString("yyyy-MM-dd")+"/",fileName = UUID.randomUUID().toString().replace("-", "")+".png";
		File file = FileUtil.mkdir(folder);
		return file.getAbsolutePath()+"/"+fileName;
	}
	/**
	 * 渲染
	 * @param chart
	 * @param width
	 * @param height
	 * @return
	 */
	public static String render(JFreeChart chart,int width,int height){
		String fileName = getTempChartImagePath();
		try {
			ChartUtilities.saveChartAsPNG(new File(fileName), chart, width, height);
			return fileName;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
